package main

import (
	"dals"
	//"database/sql"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"models"
	"net/http"
	"strconv"
	"strings"
	"time"
	"utils"

	"github.com/PuerkitoBio/goquery"
	"github.com/gin-gonic/gin"
	"golang.org/x/net/html"
)

func GetNRecby1396() {

	pre := time.Now()
	utils.Log("抓取", false, pre)
	resp, err := http.Get("http://www.1396b.com/Pk10/ajax?ajaxhandler=GetNewestRecord&t=0.3444010110106319")
	//resp, err := http.Get("http://www.1396me.com/Pk10/ajax?ajaxhandler=GetNewestRecord&t=0.3444010110106319")
	if err != nil {
		fmt.Println("http get error.")
	}
	defer resp.Body.Close()
	utils.Log("抓取", true, pre)
	pre = time.Now()
	utils.Log("分析", false, pre)
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("http read error")
	}
	var f interface{}
	json.Unmarshal(body, &f)
	m := f.(map[string]interface{})
	var bm int32
	var strDate, nums string

	for k, v := range m {
		if k == "numbers" {
			nums, _ = v.(string)
		}
		if k == "drawingTime" {
			strDate, _ = v.(string)
		}
		if k == "period" {
			bm = int32(v.(float64))
		}
	}
	strDate = fmt.Sprintf("%04d-%s", time.Now().Year(), strDate)
	arr := strings.Split(nums, ",")
	nums = ""
	for i := 0; i < 10; i++ {
		nm, _ := strconv.Atoi(arr[i])
		nums += fmt.Sprintf("%02d", nm)
	}

	fmt.Printf("bm:%d strDate:%s  nums:%s\n", bm, strDate, nums)
	utils.Log("分析", true, pre)
	pre = time.Now()
	utils.Log("存储", false, pre)
	dals.Saverec(models.Rec{Bm: int(bm), Rectime: strDate, Nums: nums})
	utils.Log("存储", true, pre)
}
func GetNRecbylecai() {
	pre := time.Now()
	utils.Log("抓取", false, pre)
	doc, err := goquery.NewDocument("http://www.lecai.com/lottery/draw/3")
	if err != nil {
		log.Fatal(err)
	}
	utils.Log("抓取", true, pre)
	pre = time.Now()
	utils.Log("分析", false, pre)
	doc.Find(".kj_box").Each(func(i int, s *goquery.Selection) {
		trs := *s.Find("a[href=\"/lottery/draw/view/557\"]").Parent().Parent().Children()
		if trs.Length() < 1 {
			log.Fatal("ddd")
		}
		bmstr := strings.Replace(strings.TrimSpace(trs.Eq(1).Text()), "期", "", 1)
		bm, err := strconv.Atoi(bmstr)
		if err != nil {
			log.Fatal(err)
		}
		strdate := strings.TrimSpace(trs.Eq(2).Text())
		trs = *trs.Eq(3).Find("span")
		var nums = ""
		for j := 0; j < 10; j++ {
			nums += strings.TrimSpace(trs.Eq(j).Text())
		}
		fmt.Printf("%d %s %s", bm, strdate, nums)
	})
	utils.Log("分析", true, pre)
}
func HasAttribute(n *html.Node, attrName, attrValue string) (exists bool) {
	for _, a := range n.Attr {
		if a.Key == attrName && a.Val == attrValue {
			return true
		}
	}
	return false
}
func Helloworld(c *gin.Context) {
	c.String(http.StatusOK, "hello world")
}
